﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace TinyAsset
{
    public class UnityHttpResponse
    {
        public bool isSuccessful;

        public bool isHttpError;

        public bool isNetworkError;

        public long responseCode;

        public string error;

        public string text;

        public byte[] data;

        public Texture2D texture;

        public AssetBundle assetBundle;

        public AudioClip audioClip;

        public Dictionary<string, string> responseHeaders;

        public static UnityHttpResponse Create(UnityWebRequest request)
        {
            UnityHttpResponse response = new UnityHttpResponse();
            response.isSuccessful = !request.isHttpError && !request.isNetworkError;
            response.isHttpError = request.isHttpError;
            response.isNetworkError = request.isNetworkError;
            response.error = request.error;
            response.responseCode = request.responseCode;
            response.responseHeaders = request.GetResponseHeaders();

            if (request.downloadHandler != null)
            {
                if (request.downloadHandler is DownloadHandlerBuffer)
                {
                    response.text = request.downloadHandler.text;
                    response.data = request.downloadHandler.data;
                }

                if (request.downloadHandler is DownloadHandlerTexture)
                    response.texture = DownloadHandlerTexture.GetContent(request);

                if (request.downloadHandler is DownloadHandlerAudioClip)
                    response.audioClip = DownloadHandlerAudioClip.GetContent(request);

                if (request.downloadHandler is DownloadHandlerAssetBundle)
                    response.assetBundle = DownloadHandlerAssetBundle.GetContent(request);
            }
            return response;
        }
    }
}